const fs = require('fs');
const path = require('path');
var tools = require('../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

const Auth = require(tools.controllerPath + 'common/auth.js');
const functions = require(tools.appPath + 'functions');

module.exports = class extends Auth {
  async __before() {
    const flag = await super.__before();
    if (flag === false) return false;

    this.moduleid = 11;
    this.MD = this.CORE_CONF.mod_single(this.moduleid);
    functions.copy_setting(this.moduleid);
    this._setting = functions.load_setting(this.moduleid);
    this.UNIQ = functions.uniq();
    this.assign({
      MODULEID: this.moduleid,
      MD: this.MD,
      UNIQ: this.UNIQ,
    });
    return true;
  }

  index(req, res) {
    res.end('article/index');
  }

  //attachment hook
  async _save_attachment(articleid, uniq, url) {
    await model.i("insert into szh_article_attachment set ?",{
      articleid: articleid,
      uniq: uniq,
      url: url,
      ts: functions.time(),
    });
  }

  async add() {
    let post = this.post();
    if (!tools.isEmpty(post)) {
      post = functions.dtrim(post);
      post['addtime'] = functions.time();
      post['edittime'] = functions.time();
      post['userid'] = this.auth['userid'];
      post['username'] = this.auth['username'];
      post['editorid'] = this.auth['userid'];
      post['editor'] = this.auth['username'];

      if (!parseInt(post['catid'])) {
        this.msg(0, '所属分类不能为空');
        return;
      }

      if (!post['title']) {
        this.msg(0, '标题不能为空');
        return;
      }

      if (!post['content']) {
        this.msg(0, '内容不能为空');
        return;
      }

      let insertid = await model.i("insert into szh_article set ?", post);
      if (insertid) {
        await model.update("update szh_article_attachment set articleid=? where uniq=?", [insertid, post['UNIQ']]);
      }
      this.msg(insertid);
      return;
    }

    let category_model = this.model('category');
    let category = await category_model.category_select(this.moduleid, 'catid', 0, '请选择', ' class="form-control" ');
    let flag = 1;

    this.assign({
      category, flag,
    });
    return this.tpl();
  }

  async lst() {
    let get = this.get();
    var { itemid, catid, title, flag } = get;
    let category_model = this.model('category');

    let where = {};
    where['flag'] = ['in', [1, 2]];
    if (typeof (itemid) == 'undefined') itemid = '';
    if (itemid) {
      where['itemid'] = itemid;
    }

    if (typeof (catid) == 'undefined') catid = 0;
    if (catid > 0) {
      where['catid'] = catid;
    }

    if (typeof (title) == 'undefined') title = '';
    if (title) {
      where['title'] = ['like', `%${title}%`];
    }

    if (typeof (flag) == 'undefined') flag = 0;
    if (flag > 0) {
      where['flag'] = flag;
    }

    let wh = model.where(where, '1=1');
    let page = typeof (get.page) != 'undefined' ? get.page : 1;
    let pagesize = parseInt(this._setting['pagesize']);
    let total = await model.value(`select count(*) from szh_article where ${wh}`);
    let data = await model.select(`select * from szh_article where ${wh} order by itemid desc limit ?,?`, [(page - 1) * pagesize, pagesize]);
    let pager = functions.pagination(this.REQUEST_URI, get, page, pagesize, total);

    for (let k = 0; k < data.length; k++) {
      let v = data[k];
      data[k]['cat'] = await category_model.get_category(v['catid']);
      data[k]['addtime'] = functions.date(v['addtime']);
    }

    let category = await category_model.category_select(this.moduleid, 'catid', catid, '请选择', ' class="form-control" ');
    this.assign({
      itemid, catid, title, flag, data, pager, category, functions
    });
    return this.tpl();
  }

  async mod() {
    let get = this.get();
    let itemid = parseInt(get.itemid);
    if (!itemid) {
      this.msg(0, 'lose itemid');
      return;
    }
    let post = this.post();
    if (!tools.isEmpty(post)) {
      let article_model = this.model('article');
      post = functions.dtrim(post);
      post['edittime'] = functions.time();
      post['editorid'] = this.auth['userid'];
      post['editor'] = this.auth['username'];

      if (!parseInt(post['catid'])) {
        this.msg(0, '所属分类不能为空');
        return;
      }

      if (!post['title']) {
        this.msg(0, '标题不能为空');
        return;
      }

      if (!post['content']) {
        this.msg(0, '内容不能为空');
        return;
      }

      let r = await model.u("update szh_article set ? where itemid=?", post, [itemid]);
      if (r !== false) {
        await model.update("update szh_article_attachment set articleid=? where uniq=?", [itemid, post['UNIQ']]);
        await article_model.treat_attachment(itemid);
      }
      this.msg(r, '', post['FORWARD']);
      return;
    }
    let data = await model.find("select * from szh_article where itemid=?", [itemid]);
    if (tools.isEmpty(data)) {
      this.msg(0, '数据不存在');
      return;
    }
    let category_model = this.model('category');
    let category = await category_model.category_select(this.moduleid, 'catid', data['catid'], '请选择', ' class="form-control" ');

    this.assign({
      category, data, functions
    });
    return this.tpl();
  }

  async del() {
    let get = this.get();
    let itemid = parseInt(get.itemid);
    if (!itemid) {
      this.msg(0, 'lose itemid');
      return;
    }
    let d = await model.find("select * from szh_article where itemid=?", [itemid]);
    if (tools.isEmpty(d)) {
      this.msg(0, '数据不存在');
      return;
    }
    //删除thumb
    //删除附件
    if (false) {
      const fs = require('fs');
      let attachments = await model.select("select * from szh_article_attachment where articleid=?", [itemid]);
      for (let i = 0; i < attachments.length; i++) {
        let v = attachments[i];
        let file = tools.rootPath + '/public'.v['url'];
        if (!fs.existsSync(file)) continue;
        fs.unlinkSync(file);
      }

      await model.delete("delete from szh_article_attachment where articleid=?", [itemid]);
    }
    let r = await model.update("update szh_article set flag=3 where itemid=?", [itemid]);
    this.msg(r === false ? false : true);
  }

  async preview() {
    let get = this.get();
    let itemid = parseInt(get.itemid);
    if (!itemid) {
      this.msg(0, 'lose itemid');
      return;
    }
    let data = await model.find("select * from szh_article where itemid=?", [itemid]);
    if (tools.isEmpty(data)) {
      this.msg(0, '数据不存在');
      return;
    }
    let category_model = this.model('category');
    let cat = await category_model.get_category(data['catid']);
    this.assign({
      data, cat, functions
    });
    return this.tpl();
  }

  async outside() {
    let get = this.get();
    var { callback, itemid, catid, title, flag } = get;

    if (typeof (callback) == 'undefined') callback = '';
    if (!callback) {
      this.msg(0, 'lose callback');
      return;
    }

    let category_model = this.model('category');

    let where = {};
    where['flag'] = ['in', [1, 2]];
    if (typeof (itemid) == 'undefined') itemid = '';
    if (itemid) {
      where['itemid'] = itemid;
    }

    if (typeof (catid) == 'undefined') catid = 0;
    if (catid > 0) {
      where['catid'] = catid;
    }

    if (typeof (title) == 'undefined') title = '';
    if (title) {
      where['title'] = ['like', `%{title}%`];
    }

    if (typeof (flag) == 'undefined') flag = 0;
    if (flag > 0) {
      where['flag'] = flag;
    }

    let wh = model.where(where, '1=1');
    let page = typeof (get.page) != 'undefined' ? get.page : 1;
    let pagesize = parseInt(this._setting['pagesize']);
    let total = await model.value(`select count(*) from szh_article where ${wh}`);
    let data = await model.select(`select * from szh_article where ${wh} order by itemid desc limit ?,?`, [(page - 1) * pagesize, pagesize]);
    let pager = functions.pagination(this.REQUEST_URI, get, page, pagesize, total);

    for (let k = 0; k < data.length; k++) {
      let v = data[k];
      data[k]['cat'] = await category_model.get_category(v['catid']);
      data[k]['addtime'] = functions.date(v['addtime']);
    }

    let category = await category_model.category_select(this.moduleid, 'catid', catid, '请选择', ' class="form-control" ');
    this.assign({
      callback, itemid, catid, title, flag, data, pager, category, functions
    });
    return this.tpl();
  }

  async setting() {
    let post = this.post();
    if (this.isPost && Object.keys(post).length > 0) {
      let r = functions.save_setting(this.moduleid, post);
      this.msg(r);
      return;
    }
    let setting = functions.load_setting(this.moduleid);
    this.assign({
      setting: setting,
    })
    return this.tpl();
  }

  async clear_attachments() {
    let attachments = await model.select("select * from szh_article_attachment where ts<? and articleid=0", [functions.time() - 86400]);

    const fs = require('fs');
    for (let i = 0; i < attachments.length; i++) {
      let v = attachments[i];
      let file = tools.rootPath + '/public' + v['url'];
      if (!fs.existsSync(file)) continue;
      fs.unlinkSync(file);
    }
    await model.delete("delete from szh_article_attachment where ts<? and articleid=0", [functions.time() - 86400]);
    this.msg(1);
    return;
  }

  async test() {
    return this.tpl();
  }

  async __call(req, res) {
    let action = this.AA;

    if (action.indexOf('category_') > -1) {
      // let category = require(tools.controllerPath + 'common/category');
      // let object = new category();
      // object.req = req;
      // object.res = res;
      // await object.init();
      // await object.__before();
      // return await object[action](req, res);
      return await this.action('category', action, tools.controllerPath + 'common');
    }

    if (action.indexOf('upload_') > -1) {
      // let upload = require(tools.controllerPath + 'common/upload');
      // let object = new upload();
      // object.req = req;
      // object.res = res;
      // await object.init();
      // await object.__before();
      // return await object[action](req, res);
      return await this.action('upload', action, tools.controllerPath + 'common');
    }
    console.log('__call', action);
  }

};
